import axios from 'axios'
import { useUserStore } from '../stores/user'
import { ElLoading, ElMessage } from 'element-plus'
import router from '../router'

let loadingInstance = null
let requestCount = 0 // 请求计数器

const isElectron = navigator.userAgent.includes('Electron')

// 使用相对路径而不是绝对路径
const service = axios.create({
  // baseURL: import.meta.env.VITE_API_BASE_URL,
  baseURL: !isElectron ? import.meta.env.VITE_API_PROXY_URL : import.meta.env.VITE_API_BASE_URL,
  timeout: 60000
})

// 请求拦截器
service.interceptors.request.use(config => {
  if (requestCount === 0) {
    loadingInstance = ElLoading.service({
      lock: true,
      text: '请求中...',
      background: 'rgba(0, 0, 0, 0.7)'
    })
  }
  requestCount++
  if (config.url?.includes('/login')) {
    return config
  }
  // const userStore = useUserStore()
  const token = localStorage.getItem('token')
  // console.log('userStore', userStore.token)
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  } else {
    console.error('No token found, please log in.')
    // 跳转路由， 回登录页
    router.replace('/login')
    return Promise.reject(new axios.Cancel('未登录，请先登录'))
  }
  return config
})

// 响应拦截器
service.interceptors.response.use(
  response => {
    requestCount--
    if (requestCount === 0) {
      loadingInstance?.close()
    }
    return response.data
  },
  error => {
    requestCount--
    if (requestCount === 0) {
      loadingInstance?.close()
    }
    const token = localStorage.getItem('token')
    console.log('error', error)
    if (token && (error.response?.status === 401 || error.response?.status === 403)) {
      const userStore = useUserStore()
      userStore.logout()
      // window.location.reload()
      router.replace('/login')
      ElMessage.error('登录已过期')
      return Promise.reject('登录已过期')
    }
    if (error.response?.status !== 200) {
      ElMessage.error(error.response.data.message)
    }
    return Promise.reject(error)
  }
)

export default service